"""
@Author：十
@Time：2025/9/5 15:55
@FileName：exception.py
@Description：仪表盘中点击显示所有异常接头
"""
import os
import sqlite3
import sys

from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QWidget, QApplication, QTableWidgetItem, QGraphicsDropShadowEffect
from loguru import logger

from details import DetailsWindow

from UI.exception import Ui_Form
import resource.WTC_rc


class ExceptionWindow(QWidget, Ui_Form):
    Signal_Refresh_Data = pyqtSignal()

    def __init__(self):
        super(ExceptionWindow, self).__init__()
        self.setupUi(self)

        self.pushButton_close.clicked.connect(self.close)

        self.Signal_Refresh_Data.connect(self.Refresh_Data)

        self.tableWidget.cellClicked.connect(self.show_detailsWindow)

        self.initInterface()

        self.Refresh_Data()
    def resource_path(self, relative_path):
        """获取资源文件的绝对路径"""
        try:
            # PyInstaller创建临时文件夹，将路径存储在_MEIPASS中
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)
    def showWindow(self):
        self.show()

    def initInterface(self):
        self.setWindowFlags(Qt.FramelessWindowHint)

        self.tableWidget.setSortingEnabled(True)

    # 刷新数据
    def Refresh_Data(self):
        try:
            # 从数据库读
            conn = sqlite3.connect(self.resource_path('db/WTC.db'))
            cursor = conn.cursor()
            read_table_exception = """
                         SELECT 
                            d.joints,
                            t.sensor_id,
                            t.inner_temperature,
                            t.external_temperature,
                            t.ambient_temps,
                            t.timestamp,
                            d.state 
                        FROM device_db d
                        LEFT JOIN (
                            SELECT 
                                sensor_id,
                                inner_temperature,
                                external_temperature,
                                ambient_temps,
                                timestamp,
                                ROW_NUMBER() OVER (PARTITION BY sensor_id ORDER BY timestamp DESC) AS rn
                            FROM temperature_db
                        ) t ON d.sensor_id = t.sensor_id AND t.rn = 1
                        WHERE d.state NOT IN ('正常', '环境')
                        """
            cursor.execute(read_table_exception)
            exception_data = cursor.fetchall()

            self.tableWidget.setRowCount(0)

            # 设置行数
            self.tableWidget.setRowCount(len(exception_data))

            # 插入数据到tableWidget
            for row_idx, row_data in enumerate(exception_data):
                for col_idx, cell_data in enumerate(row_data):
                    item = QTableWidgetItem(str(cell_data) if cell_data is not None else "")
                    item.setTextAlignment(Qt.AlignCenter)
                    if col_idx == 6 and cell_data not in ["正常", "环境"]:
                        item.setForeground(Qt.red)
                    elif col_idx == 6 and cell_data == "正常":
                        item.setForeground(Qt.green)

                    self.tableWidget.setItem(row_idx, col_idx, item)

            # 调整列宽
            self.tableWidget.resizeColumnsToContents()
            self.tableWidget.resizeRowsToContents()

        except Exception as e:
            logger.critical(f'获取异常列表错误：{e}')
            print('获取异常列表错误:', e)

    def show_detailsWindow(self, row, column):
        try:
            # 获取该行的所有列数据
            row_data = []
            for col in range(self.tableWidget.columnCount()):
                item = self.tableWidget.item(row, col)
                if item is not None:
                    row_data.append(item.text())
                else:
                    row_data.append("")

            # 创建详情窗口并传递数据
            self.detailsWindow = DetailsWindow()
            self.detailsWindow.set_data(row_data)
            self.detailsWindow.show()

        except Exception as e:
            logger.critical(f'呼出详情窗口错误：{e}')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainWindow = ExceptionWindow()
    mainWindow.show()
    sys.exit(app.exec_())
